<template>
  <div class="course-container">
    <el-card class="course-card">
      <template #header>
        <div class="course-header">
          <h1>课程管理</h1>
          <el-form :inline="true" class="course-filter" @submit.prevent="searchCourse">
            <el-form-item label="课程名称">
              <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" clearable />
            </el-form-item>
            <el-form-item label="课程排序">
              <el-input-number 
                v-model="searchForm.courseSort" 
                placeholder="请输入课程排序"
                :min="1"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchCourse" :loading="loading">查询</el-button>
              <el-button type="success" @click="showAddModal" :loading="loading">新增课程</el-button>
              <el-button type="info" @click="exportToExcel" :loading="loading">导出Excel</el-button>
              <el-button 
                type="danger" 
                @click="batchDelete" 
                :loading="loading" 
                :disabled="selectedCourses.length === 0"
              >
                批量删除
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table 
        :data="courseList" 
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"  :selectable="isSelectable"/>
        <el-table-column prop="courseName" label="课程名称" min-width="200" />
        <el-table-column prop="courseAuthor" label="课程作者" width="120" />
        <el-table-column prop="courseIntro" label="课程简介" min-width="200" show-overflow-tooltip />
        <el-table-column prop="courseSort" label="课程排序" width="100" />
        <!-- 审核状态列 - 所有用户可见 -->
        <el-table-column label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getReviewStatusType(scope.row.courseStatus)">
              {{ getReviewStatusText(scope.row.courseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" type="info" @click="viewDetail(scope.row)">查看</el-button>
              <!-- 编辑按钮 - 只有管理员或课程创建者可以编辑 -->
              <el-button 
                v-if="isAdmin || scope.row.createPersonId === currentUserId" 
                size="small" 
                type="warning" 
                @click="editCourse(scope.row)"
              >
                编辑
              </el-button>
              
              <!-- 审核操作下拉菜单 - 只有管理员可见，且只对未审核的课程显示 -->
              <el-dropdown 
                v-if="isAdmin && scope.row.courseStatus === 0" 
                @command="handleReviewCommand"
              >
                <el-button size="small" type="success">
                  审核操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'approve', courseId: scope.row.courseId}">
                      <el-icon><check /></el-icon>审核通过
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'reject', courseId: scope.row.courseId}">
                      <el-icon><close /></el-icon>审核拒绝
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              
              <!-- 删除按钮 - 只有管理员或课程创建者可以删除 -->
              <el-button 
                v-if="isAdmin || scope.row.createPersonId === currentUserId" 
                size="small" 
                type="danger" 
                @click="deleteCourseItem(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="10"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      v-model="showModal" 
      :title="isEdit ? '编辑课程' : '新增课程'"
      width="800px"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程作者" prop="courseAuthor">
          <el-input v-model="formData.courseAuthor" placeholder="请输入课程作者" />
        </el-form-item>
        <el-form-item label="课程简介" prop="courseIntro">
          <el-input 
            v-model="formData.courseIntro" 
            type="textarea" 
            :rows="3"
            placeholder="请输入课程简介" 
          />
        </el-form-item>
        <el-form-item label="课程排序" prop="courseSort">
          <el-input-number 
            v-model="formData.courseSort" 
            :min="1"
            placeholder="请输入课程排序，数字越小越靠前" 
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="courseCover">
          <div class="image-upload-container">
            <el-input 
              v-model="formData.courseCover" 
              placeholder="请输入封面名称或选择封面图片"
              readonly
              class="image-input"
            />
            <el-button 
              type="primary" 
              @click="selectImage"
              class="select-image-btn"
            >
              选择封面
            </el-button>
            <input 
              ref="fileInput"
              type="file" 
              accept="image/*"
              style="display: none"
              @change="handleImageSelect"
            />
          </div>
          <div class="form-tip">支持 jpg、png、gif 等图片格式</div>
          <div v-if="formData.courseCover" class="image-preview">
            <img 
              :src="getImageUrl(formData.courseCover)" 
              :alt="formData.courseCover"
              @error="handleImageError"
            />
            <span class="image-name">{{ formData.courseCover }}</span>
          </div>
        </el-form-item>
        <el-form-item label="课程视频" prop="courseVideo">
          <div class="video-upload-container">
            <el-input 
              v-model="formData.courseVideo" 
              placeholder="请选择课程视频文件"
              readonly
              class="video-input"
            />
            <el-button 
              type="primary" 
              @click="selectVideo"
              class="select-video-btn"
            >
              选择视频
            </el-button>
            <input 
              ref="videoInput"
              type="file" 
              accept="video/mp4"
              style="display: none"
              @change="handleVideoSelect"
            />
          </div>
          <div class="form-tip">支持 mp4 格式视频文件</div>
          <div v-if="formData.courseVideo" class="video-preview">
            <span class="video-name">{{ formData.courseVideo }}</span>
            <el-button size="small" type="danger" @click="removeVideo">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="showDetailModal" 
      title="课程详情"
      width="800px"
    >
      <div v-if="currentCourse" class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程ID">{{ currentCourse.courseId }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ currentCourse.courseName }}</el-descriptions-item>
          <el-descriptions-item label="课程作者">{{ currentCourse.courseAuthor }}</el-descriptions-item>
          <el-descriptions-item label="创建人ID">{{ currentCourse.createPersonId }}</el-descriptions-item>
          <el-descriptions-item label="课程排序">{{ currentCourse.courseSort }}</el-descriptions-item>
          <!-- 审核状态 - 所有用户可见 -->
          <el-descriptions-item label="审核状态">
            <el-tag :type="getReviewStatusType(currentCourse.courseStatus)">
              {{ getReviewStatusText(currentCourse.courseStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="课程简介" :span="2">{{ currentCourse.courseIntro }}</el-descriptions-item>
          <el-descriptions-item label="课程封面" :span="2">
            <el-image 
              v-if="currentCourse.courseCover" 
              :src="getImageUrl(currentCourse.courseCover)" 
              :alt="currentCourse.courseName"
              style="max-width: 200px; max-height: 150px"
              fit="cover"
              :preview-src-list="[getImageUrl(currentCourse.courseCover)]"
            >
              <template #error>
                <div class="image-error">加载失败</div>
              </template>
            </el-image>
            <span v-else>无封面</span>
          </el-descriptions-item>
          <el-descriptions-item label="课程视频" :span="2">
            <div v-if="currentCourse.courseVideo" class="video-detail">
              <video 
                :src="getVideoUrl(currentCourse.courseVideo)" 
                controls
                style="max-width: 400px; max-height: 300px"
              >
                您的浏览器不支持视频播放
              </video>
              <div class="video-info">
                <span class="video-name">{{ currentCourse.courseVideo }}</span>
              </div>
            </div>
            <span v-else>无视频</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Check, Close } from '@element-plus/icons-vue'
import CourseService from '../services/CourseService'
import UserService from '../services/UserService.js'

// 响应式数据
const courseList = ref([])
const selectedCourses = ref([])
const loading = ref(false)
const showModal = ref(false)
const showDetailModal = ref(false)
const isEdit = ref(false)
const currentCourse = ref(null)
const formRef = ref()
const fileInput = ref(null)
const videoInput = ref(null)

// 分页相关数据
const currentPage = ref(1)
const total = ref(0)

// 当前用户信息 - 使用UserService
const currentUserId = computed(() => UserService.getCurrentUserId())
const isAdmin = computed(() => UserService.isAdmin())

const isSelectable = computed(() => {
  return (row) => {
    // 如果是管理员，所有行都可选
    const currentUserStr = localStorage.getItem('currentUser');

    if (JSON.parse(currentUserStr).userType === 2) return true
    
    // 否则，只有自己创建的课程可选
    return row.createPersonId === currentUserId.value
  }
})

const searchForm = reactive({
  courseName: '',
  courseSort: null
})

const formData = reactive({
  courseId: null,
  courseName: '',
  courseIntro: '',
  courseCover: '',
  courseSort: null,
  courseVideo: '',
  courseAuthor: '',
  createPersonId: 1
})

// 表单验证规则
const rules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  courseIntro: [
    { required: true, message: '请输入课程简介', trigger: 'blur' }
  ],
  courseSort: [
    { required: true, message: '请输入课程排序', trigger: 'blur' }
  ],
  courseAuthor: [
    { required: true, message: '请输入课程作者', trigger: 'blur' }
  ]
}

// 计算属性
const isAllSelected = computed(() => {
  return courseList.value.length > 0 && selectedCourses.value.length === courseList.value.length
})

// 方法
const loadCourseList = async () => {
  loading.value = true
  try {
    const params = { current: currentPage.value }
    const response = await CourseService.getCourseListWithPage(params)
    if (response.code === 200) {
      const pageData = response.data
      courseList.value = pageData.records || []
      total.value = pageData.total || 0
      
      courseList.value.forEach(course => {
        if (course.courseStatus === undefined || course.courseStatus === null) {
          course.courseStatus = 0
        }
      })
    } else {
      ElMessage.error(response.message || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

const searchCourse = async () => {
  loading.value = true
  try {
    const params = { current: currentPage.value }
    
    Object.keys(searchForm).forEach(key => {
      if (searchForm[key]) {
        params[key] = searchForm[key]
      }
    })
    
    const response = await CourseService.getCourseListWithPage(params)
    if (response.code === 200) {
      const pageData = response.data
      courseList.value = pageData.records || []
      total.value = pageData.total || 0
      
      courseList.value.forEach(course => {
        if (course.courseStatus === undefined || course.courseStatus === null) {
          course.courseStatus = 0
        }
      })
    } else {
      ElMessage.error(response.message || '搜索课程失败')
    }
  } catch (error) {
    console.error('搜索课程失败:', error)
    ElMessage.error('搜索课程失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'courseSort' ? null : ''
  })
  currentPage.value = 1
  loadCourseList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadCourseList()
}

const handleSelectionChange = (selection) => {
  selectedCourses.value = selection
}

const showAddModal = () => {
  isEdit.value = false
  resetForm()
  showModal.value = true
}

const editCourse = (course) => {
  isEdit.value = true
  Object.assign(formData, course)
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    courseId: null,
    courseName: '',
    courseIntro: '',
    courseCover: '',
    courseSort: null,
    courseVideo: '',
    courseAuthor: '',
    createPersonId: 1
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const courseData = { ...formData }
    
    if (isEdit.value) {
      const response = await CourseService.updateCourse(courseData)
      if (response.code === 200) {
        ElMessage.success('修改课程成功')
        closeModal()
        loadCourseList()
      } else {
        ElMessage.error(response.message || '修改课程失败')
      }
    } else {
      const response = await CourseService.addCourse(courseData)
      if (response.code === 200) {
        ElMessage.success('新增课程成功')
        closeModal()
        loadCourseList()
      } else {
        ElMessage.error(response.message || '新增课程失败')
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交表单失败')
  }
}

const deleteCourseItem = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程"${course.courseName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await CourseService.deleteCourse(course.courseId)
    if (response.code === 200) {
      ElMessage.success('删除课程成功')
      loadCourseList()
    } else {
      ElMessage.error(response.message || '删除课程失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

const batchDelete = async () => {
  if (selectedCourses.value.length === 0) {
    ElMessage.warning('请选择要删除的课程')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedCourses.value.length} 门课程吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const courseIds = selectedCourses.value.map(course => course.courseId)
    const response = await CourseService.batchDeleteCourse(courseIds)
    if (response.code === 200) {
      ElMessage.success(response.message)
      loadCourseList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const viewDetail = async (course) => {
  try {
    const response = await CourseService.getCourseDetail(course.courseId)
    if (response.code === 200) {
      currentCourse.value = response.data
      showDetailModal.value = true
    } else {
      ElMessage.error(response.message || '获取课程详情失败')
    }
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败')
  }
}

const handleReviewCommand = async (command) => {
  try {
    const { action, courseId } = command
    const status = action === 'approve' ? 1 : 2
    
    const response = await CourseService.reviewCourse(courseId, status)
    if (response.code === 200) {
      ElMessage.success(response.message || '审核操作成功')
      loadCourseList()
    } else {
      ElMessage.error(response.message || '审核操作失败')
    }
  } catch (error) {
    console.error('审核操作失败:', error)
    ElMessage.error('审核操作失败')
  }
}

const exportToExcel = async () => {
  try {
    await CourseService.exportExcel(courseList.value)
    ElMessage.success('导出Excel成功')
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage.error('导出Excel失败')
  }
}

// 图片相关方法
const selectImage = () => {
  fileInput.value.click()
}

const handleImageSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }
    
    // 验证文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB')
      return
    }
    
    formData.courseCover = file.name
    ElMessage.success(`已选择图片: ${file.name}`)
  }
  event.target.value = ''
}

const handleImageError = () => {
  ElMessage.warning('图片加载失败')
}

const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/images/${imagePath}`
}

// 视频相关方法
const selectVideo = () => {
  videoInput.value.click()
}

const handleVideoSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.type !== 'video/mp4') {
      ElMessage.error('请选择MP4格式的视频文件')
      return
    }
    
    // 验证文件大小（限制为100MB）
    if (file.size > 100 * 1024 * 1024) {
      ElMessage.error('视频文件大小不能超过100MB')
      return
    }
    
    formData.courseVideo = file.name
    ElMessage.success(`已选择视频: ${file.name}`)
  }
  event.target.value = ''
}

const removeVideo = () => {
  formData.courseVideo = ''
}

const getVideoUrl = (videoPath) => {
  if (!videoPath) return ''
  return `/images/${videoPath}`
}

// 审核状态相关方法
const getReviewStatusText = (status) => {
  return CourseService.getReviewStatusText(status)
}

const getReviewStatusType = (status) => {
  return CourseService.getReviewStatusType(status)
}

// 生命周期
onMounted(() => {
  UserService.loadCurrentUser();
  loadCourseList()
})
</script>

<style scoped>
.course-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-section {
  margin-bottom: 20px;
}

.action-section {
  margin-bottom: 20px;
}

.action-section .el-button {
  margin-right: 10px;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
}

.image-upload-container,
.video-upload-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-input,
.video-input {
  flex: 1;
}

.select-image-btn,
.select-video-btn {
  white-space: nowrap;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.image-preview,
.video-preview {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-preview img {
  max-width: 100px;
  max-height: 60px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.image-name,
.video-name {
  font-size: 12px;
  color: #606266;
}

.image-error {
  color: #f56c6c;
  font-size: 12px;
}

.video-detail {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.course-detail {
  max-height: 600px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .course-container {
    padding: 10px;
  }
  
  .operation-buttons {
    flex-direction: column;
  }
  
  .image-upload-container,
  .video-upload-container {
    flex-direction: column;
    align-items: stretch;
  }
}
</style> 